package org.realogic.cfm.spring;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

public class GlobalExceptionResolver extends SimpleMappingExceptionResolver {

	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		String viewName = determineViewName(ex, request);
		if (viewName != null) {
			boolean flag = request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1;
			if (!flag) {
				flag = request.getHeader("accept").indexOf("application/json") > -1;
			}
			if (flag) {
				// JSON格式返回
				//MappingJacksonJsonView jsonView = new MappingJacksonJsonView();
				//return new ModelAndView(jsonView, "错误", ex.getLocalizedMessage());
				return getModelAndView(viewName, ex, request);
			} else {
				// JSP格式返回
				// 如果不是异步请求
				// Apply HTTP status code for error views, if specified.
				// Only apply it if we're processing a top-level request.
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				return getModelAndView(viewName, ex, request);
			}
		} else {
			return null;
		}
	}
}
